package com.rdiot.yx485.ui.ctrl

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.drake.net.scope.AndroidScope
import com.drake.net.utils.scopeNetLife
import com.jaygoo.widget.OnRangeChangedListener
import com.jaygoo.widget.RangeSeekBar
import com.king.zxing.util.LogUtils
import com.lindroy.iosdialog.IBottomListDialog
import com.rdiot.yx485.R
import com.rdiot.yx485.base.BaseFragment
import com.rdiot.yx485.base.LocalData
import com.rdiot.yx485.base.RoomCtrlViewModelFactory
import com.rdiot.yx485.databinding.FraSubRoomCtrlBinding
import com.rdiot.yx485.net.*
import com.rdiot.yx485.ui.ctrl.model.RoomCtrlViewModel
import com.rdiot.yx485.ui.web.WebActivity
import com.rdiot.yx485.util.*
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay

/**
 * 子控房间控制
 * @author mR2hao
 * @date 2022/11/18
 */
class SubRoomCtrlFragment : BaseFragment<FraSubRoomCtrlBinding>(), ClickLimitListener,
    ClickAlphaListener {

    override fun getLayoutId() = R.layout.fra_sub_room_ctrl
    private val viewModel: RoomCtrlViewModel by activityViewModels { RoomCtrlViewModelFactory() }

    private var pollJob: Job? = null
    private var tempScope: AndroidScope? = null


    companion object {

        /** 轮询间隔 */
        private const val POLL_REFRESH_TIME = 3

        /** 设置温度偏移量 */
        private const val TEMP_OFFSET = 16

        /** 监听次数 */
        private const val OBSERVE_COUNT = 2

        private const val MAX_TEMP = 30
        private const val MIN_TEMP = 16
    }

    private var level: Int = 0

    @SuppressLint("ClickableViewAccessibility")
    override fun initView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ) {

        binding.nb.setLeftClickListener { act.finish() }
        binding.nb.setRightClickListener {
            findNavController().navigate(R.id.action_subRoomCtrlFragment_to_roomSettingFragment)
        }


        initCtrlViews()

        viewModel.roomData.observe(this) {
            binding.roomData = it
            binding.nb.setTitle(it.name)
            binding.arcSeekBar.progress = it.setTemp - TEMP_OFFSET
            binding.rangeSeekBar.setProgress(it.fanValue.toFloat() - 1)
        }

        startPoll()
    }

    private fun initCtrlViews() {
        binding.llSwitch.setClickLimitListener(this)
        binding.tvHomeHumidity2.setClickLimitListener(this)
        binding.tvHomeTemp2.setClickLimitListener(this)

        //风速
        binding.rangeSeekBar.setOnRangeChangedListener(object : OnRangeChangedListener {
            override fun onRangeChanged(
                view: RangeSeekBar?,
                leftValue: Float,
                rightValue: Float,
                isFromUser: Boolean
            ) {
            }

            override fun onStartTrackingTouch(view: RangeSeekBar?, isLeft: Boolean) {
            }

            override fun onStopTrackingTouch(view: RangeSeekBar?, isLeft: Boolean) {
                val data = viewModel.roomData.value ?: return
                val windSpeed = (view?.leftSeekBar?.progress!! + 1).toInt()
                LogUtils.e("设置风速:$windSpeed")

                scopeNetLife {
                    setWindSpeed(
                        LocalData.familyData.value?.gateway ?: "",
                        data,
                        windSpeed,
                        RoomUtils.isMaster(viewModel.roomData.value?.code)
                    ).await()
                }
            }

        })
    }


    override fun onClickLimit(view: View) {
        viewClicked(view)
    }

    override fun onClickAlpha(view: View) {
        viewClicked(view)
    }

    private fun viewClicked(view: View) {
        val data = viewModel.roomData.value ?: return
        when (view) {
            binding.llSwitch -> {   //总开关
                data.power = !data.power
                scopeNetLife {
                    setPower(LocalData.familyData.value?.gateway ?: "", data).await()
                }
            }
            binding.tvHomeHumidity2 -> {
                goDataChart("湿度", "humidity")
            }

            binding.tvHomeTemp2 -> {
                goDataChart("温度","temp")
            }
            else -> {}
        }
        viewModel.roomData.postValue(data)
        LocalData.lastRefreshTime = curTime
    }


    /** 开始轮询  最低 [POLL_REFRESH_TIME] 间隔*/
    private fun startPoll() {
        if (pollJob == null) {
            var scope: AndroidScope? = null
            pollJob = lifecycleScope.launchWhenResumed {
                while (!act.isFinishing) {
                    val last = LocalData.lastRefreshTime
                    val less = (POLL_REFRESH_TIME - (curTime - last) / 1000).coerceAtLeast(0)
                    if (less == 0L) {
                        scope?.cancel() // 如果存在则取消
                        scope = scopeNetLife {

                            scopeNetLife {
                                viewModel.roomData.value?.recordId?.let {
                                    val data = getRoomInfo(it).await()
                                    viewModel.roomData.postValue(data)
                                }
                            }
                            LocalData.lastRefreshTime = curTime
                        }
                    }
                    delay(1000)
                }
            }
        }
    }

    //跳转到数据曲线页面
    private fun goDataChart(typeName: String, type: String) {
        act.clearGoTo(
          WebActivity.getNewWebIntent(
                act,
                "https://app.yongxulvjian.com/#/DataChart/${viewModel.roomData.value?.recordId}/${type}",
                typeName
            )
        )
    }
}